package com.cskaoyan.wx.controller;

import com.cskaoyan.bean.Cart;
import com.cskaoyan.utils.UserUtils;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.wx.bean.Checkout;
import com.cskaoyan.wx.bo.CartDeleteBO;
import com.cskaoyan.wx.bo.CartUpdateBO;
import com.cskaoyan.wx.bo.ChooseOrDeleteGoods;
import com.cskaoyan.wx.service.WxCartService;
import com.cskaoyan.wx.vo.CartIndexVO;
import com.cskaoyan.wx.vo.CheckoutVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Random;

@RestController
@RequestMapping("wx/cart")
public class WxCartController {

    @Autowired
    WxCartService wxCartService;

    @GetMapping("index")
    public BaseRespVo cartIndex() {
        Integer userId = UserUtils.getUserId();
        CartIndexVO cartIndexVO = wxCartService.getCartList(userId);
        return BaseRespVo.ok(cartIndexVO);
    }

    @PostMapping("checked")
    public BaseRespVo cartChecked(@RequestBody ChooseOrDeleteGoods chooseOrDeleteGoods) {
        CartIndexVO cartIndexVO = wxCartService.cartChecked(chooseOrDeleteGoods);
        return BaseRespVo.ok(cartIndexVO);
    }

    @PostMapping("delete")
    public BaseRespVo cartDelete(@RequestBody CartDeleteBO cartDeleteBO) {
        CartIndexVO cartIndexVO = wxCartService.cartDelete(cartDeleteBO);
        return BaseRespVo.ok(cartIndexVO);
    }

    @GetMapping("goodscount")
    public BaseRespVo goodsCount() {
        Integer userId = UserUtils.getUserId();
        Integer count = wxCartService.goodsCount(userId);
        return BaseRespVo.ok(count);
    }

    @PostMapping("add")
    public BaseRespVo addCart(@RequestBody Cart cart) {
        Integer count = wxCartService.addCart(cart);
        return BaseRespVo.ok(count);
    }

    @PostMapping("update")
    public BaseRespVo update(@RequestBody CartUpdateBO cartUpdateBO) {
        Integer number = cartUpdateBO.getNumber();
        if (number == 1) {
            BaseRespVo.ok();
        }
        wxCartService.cartUpdate(cartUpdateBO);
        return BaseRespVo.ok();
    }

    @PostMapping("fastadd")
    public BaseRespVo fastadd(@RequestBody CartUpdateBO cartUpdateBO, HttpSession httpSession) {
        int id = new Random().nextInt(Integer.MAX_VALUE);
        httpSession.setAttribute("cart_"+id,cartUpdateBO);
//       Integer cartId =  wxCartService.fastadd(cartUpdateBO);
       return BaseRespVo.ok(id);
    }

    @GetMapping("checkout")
    public BaseRespVo checkout(Checkout checkout) {
        CheckoutVO checkoutVO = wxCartService.checkout(checkout);
        return BaseRespVo.ok(checkoutVO);
    }
}
